const Router = require("@koa/router");
const router = new Router();
const {User} = require('../database/index')
const jwt = require('jsonwebtoken')

//1. 注册 / 编辑
router.post('/register_edit', async ctx => {

  let {userId} = ctx.query;
  let {account, password, name, photo, sex, birth, introduce, hobby,collect} = ctx.request.body;

  if (userId) {
    //    编辑
    const user = await User.update({
      account, password, name, photo, sex, birth, introduce, hobby,collect
    }, {
      where: {
        userId
      }
    })
    // 数据库有userId返回 [1]，没有[0]
    if (user[0]) {
      ctx.body = {
        code: '200',
        msg: '修改成功',
        data: '修改成功'
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '修改失败',
        data: '修改失败'
      }
    }
  } else {
    //    注册
    const user = await User.create({
      account, password, name, photo, sex, birth, introduce, hobby,collect
    })
    if (user) {
      ctx.body = {
        code: '200',
        msg: '注册成功',
        data: user
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '注册失败',
        data: '注册失败'
      }
    }
  }

})

//2. 登录
router.post('/login', async ctx => {
  const {account, password} = ctx.request.body;
  const user = await User.findOne({
    where: {
      account, password
    }
  })
  if (user) {
    const {account, name, photo, sex, birth, introduce, hobby,collect} = user
    const token = jwt.sign(
      {account, name, photo, sex, birth, introduce, hobby,collect},
      "music",
      {
        expiresIn: 3600 * 24 * 7,
      }
    );
    ctx.body = {
      code: '200',
      msg: 'success',
      data: {
        token,
        user
      }
    }
  } else {
    ctx.body = {
      code: '500',
      msg: '登录失败',
      data: '登录失败'
    }
  }
})

//3. 查看all/userId
router.get('/getUser', async ctx => {
  const {userId} = ctx.query;
  if (userId) {
    const user = await User.findOne({
      where: {
        userId
      }
    })

    if (user) {
      ctx.body = {
        code: '200',
        msg: '查看成功',
        data: user
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '查询失败',
        data: "查询失败"
      }
    }
  } else {
    const user = await User.findAll();
    if (user) {
      ctx.body = {
        code: '200',
        msg: '查看成功',
        data: user
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '查询失败',
        data: "查询失败"
      }
    }
  }


})

//4. 删除some/userId
router.get('/deleteUser', async ctx => {
  const {userId} = ctx.request.query;
  const userIds = Array.of(userId)
  if (userId.length > 0) {
    for (let userId of userIds) {
      await User.destroy({
        where: {
          userId
        }
      })
    }
    ctx.body = {
      code: '200',
      msg: '删除成功',
      data: '删除成功'
    }
  } else {
    ctx.body = {
      code: '500',
      msg: '删除失败',
      data: '删除失败'
    }
  }
})

module.exports = router